package com.framework.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.model.StaffInfoModel;
import com.common.utils.SysConfig;

/**
 * 用户认证过滤器
 * 
 * @author XUFENG
 * @date 2007-9-17 下午02:01:09
 * 
 */
public class AuthorizeFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 7833573124605117900L;

	private static final String loginServlet = "/login.do";
	protected FilterConfig filterConfig = null;

	protected boolean useFilter = false;

	public AuthorizeFilter() {
		System.out.println("[INFO] AuthorizeFilter Loaded.");
	}

	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {

		try {
			HttpServletRequest req = (HttpServletRequest) request;
			//String requestIP = req.getRemoteAddr();
			String requestURI = req.getRequestURI();
			//String queryString = req.getQueryString();
			String contextPath = req.getContextPath();
			if((requestURI.equals(contextPath+"/"))){
				HttpServletResponse rep = (HttpServletResponse) response;
				rep.sendRedirect(contextPath + "/login.jsp");
			}

			Object o = req.getSession().getAttribute(
					SysConfig.ATTRIBUTE_USER_KEY);

			// 如果web.xml里的useFilter配置不为true
			if (!this.useFilter) {
				filterChain.doFilter(request, response);
			} else if (o == null ||  !(o instanceof StaffInfoModel)) {
				// 如果是登陆页不要验证
				if (requestURI.endsWith(loginServlet)) {
					filterChain.doFilter(request, response);
					return;
				} else {
					// 如果为登陆访问,跳转到登录页面
					HttpServletResponse rep = (HttpServletResponse) response;
					rep.sendRedirect(contextPath + "/login.jsp");
				}

			} else {
				// 已经登陆,继续此次请求
				filterChain.doFilter(request, response);
			}

		} catch (Exception e) {
			filterConfig.getServletContext().log(e.getMessage());
		}

	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		String useFilter = filterConfig.getInitParameter("useFilter");
		if (useFilter != null && useFilter.trim().toLowerCase().equals("true")) {
			this.useFilter = true;
		}
	}

	public void destroy() {
		this.filterConfig = null;
		this.useFilter = false;
	}
}
